package cn.com.cc.parse;

import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.com.cc.log.Logger;

public class XMLDecoder {
	/**
	 * 
	 * @param xmlPath			xml文件路径
	 * @param position			解析位置,参考Constants HEADER CONTENT TAIL
	 * @return
	 */
	public Map decoderFromFile(String xmlPath, String position){
		Document doc = parseDoc(xmlPath, "UTF-8", true);
		Element mapElement = getElement(doc, position);
		return getMap(mapElement);
	}
	/**
	 * 
	 * @param s					xml内容,字符串形式
	 * @param position			解析位置,参考Constants HEADER CONTENT TAIL
	 * @return
	 */
	public Map decoderFromStr(String s, String position){
		Document doc = parseDoc(s, "UTF-8", false);
		Element mapElement = getElement(doc, position);
		return getMap(mapElement);
	}
	
	private Document parseDoc(String s, String encoding, boolean flag){
		Document doc = null;
		try {
			SAXReader reader = new SAXReader();
			if(flag){				//解析的内容是xml文件路径
				if("UTF-8".equals(encoding)){
					InputStream in = new FileInputStream(s);
					reader.setEncoding(encoding);
					doc = reader.read(in);
				}
			}else{					//解析的内容是xml字符串
				if("UTF-8".equals(encoding)){
					reader.setEncoding(encoding);
					doc = reader.read(new ByteArrayInputStream(s.getBytes()));
				}
			}
			
		} catch (FileNotFoundException e) {
			Logger.debug(new StringBuffer().append("###cn.com.parse.XMLDecoder.parseDoc(String path, String encoding)--->xml文件路径有误").toString());
			e.printStackTrace();
		} catch (DocumentException e1) {
			Logger.debug(new StringBuffer().append("###cn.com.parse.XMLDecoder.parseDoc(String path, String encoding)--->SAX读取流有误").toString());
			e1.printStackTrace();
		}
		return doc;
	}
	
	
	private Element getElement(Document doc, String position){
		Element rootElement = doc.getRootElement();
		System.out.println(rootElement.getName());
		Element positionElement = rootElement.element(position);
		System.out.println(positionElement.getName());
		if(positionElement == null){
			return null;
		}else{
			return positionElement.element("Map");
		}
	}
	
	private Map getMap(Element mapElement){
		if(mapElement == null){
			return null;
		}else{
			Map map = new LinkedHashMap();
			return recursion(mapElement, map);
		}
	}
	
	private Map recursion(Element mapElement, Map map){
		if(mapElement == null){
			return null;
		}else{
			Element itemElement = null;
			for(Iterator it = mapElement.elementIterator();it.hasNext();getValue(itemElement, map)){
				itemElement = (Element) it.next();
//				System.out.println(itemElement.getName());
			}
//			System.out.println("size::::" +map.size());
			return map;
		}
	}
	
	private void getValue(Element itemElement, Map map){
		Element valueElement = itemElement.element("Value");
		if(valueElement.isTextOnly()){
			String value = getText(valueElement);
//			System.out.println("key:::: "+ itemElement.element("Key").getText());
//			System.out.println("value:::" + value);
			map.put(getText(itemElement.element("Key")), value);
		}else{
			Map nextMap = new  LinkedHashMap();
			recursion(valueElement, nextMap);
			map.put(getText(itemElement.element("Key")), nextMap);
		}
	}
	
	
	private String getText(Element valueElement){
		String text = valueElement.getText();
		if(text == null || "NULL".equalsIgnoreCase(text)){
			return null;
		}
		return text.trim();
	}
	
	public static void main (String[] args){
		XMLDecoder decoder = new XMLDecoder();
		System.out.println(XMLDecoder.class.getResource("a.xml").getPath());
//		Map contentMap = decoder.decoderFromFile(XMLDecoder.class.getResource("a.xml").getPath(), "CONTENT");
		Map contentMap = decoder.decoderFromStr("<Message><HEAD><Map><Item><Key>aaa</Key><Value></Value></Item><Item><Key>bbb</Key><Value>222</Value></Item></Map></HEAD><CONTENT><Map><Item><Key>ccc</Key><Value>333</Value></Item><Item><Key>ddd</Key><Value>444</Value></Item><Item><Key>jjj</Key><Value><Item><Key>ggg</Key><Value>777</Value></Item><Item><Key>hhh</Key><Value>888</Value></Item><Item><Key>iii</Key><Value>999</Value></Item></Value></Item></Map></CONTENT><TAIL><Map><Item><Key>eee</Key><Value>嘿嘿</Value></Item><Item><Key>fff</Key><Value>666</Value></Item></Map></TAIL></Message>", "HEAD");
		for(Iterator it = contentMap.keySet().iterator(); it.hasNext(); ){
			String key = (String) it.next();
			System.out.println(key);
			if("jjj".equals(key)){
				System.out.println(((Map) contentMap.get(key)).size());
			}
			if(key == null){
				System.out.println("aaaaaaaa null");
			}
			System.out.println(contentMap.get(key));
		}
		Map dataMap = (Map) contentMap.get("AttachmentList");
		if(dataMap != null && dataMap.size() > 0){
			for(Iterator it = dataMap.keySet().iterator();it.hasNext();){
				String key = (String)it.next();
				System.out.println(":::::::" + key);
				System.out.println(":::::::" + dataMap.get(key));
			}
		}
		
	}

}
